package com.huanzhidadi.logaspect.aspect;

import com.alibaba.fastjson2.JSON;
import com.huanzhidadi.logaspect.annotation.ThirdLogAnno;
import com.huanzhidadi.logaspect.model.ThirdLogDO;
import com.huanzhidadi.logaspect.service.ThirdLogDOService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

@Slf4j
@Component
@Aspect
public class ThirdLogAspect {
    // 线程的局部变量，用于解决多线程中相同变量的访问冲突问题
    public static ThreadLocal<ThirdLogDO> thirdLogThreadLocal = new ThreadLocal<>();

    @Autowired
    private ThirdLogDOService thirdLogDOService;

    // 配置织入点 annotation方法 within类
    @Pointcut("@annotation(com.huanzhidadi.logaspect.annotation.ThirdLogAnno)")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        ThirdLogDO thirdLogDO = new ThirdLogDO();
        thirdLogThreadLocal.set(thirdLogDO);
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得注解
            ThirdLogAnno thirdLogAnno = getAnnotationLog(joinPoint);
            if (thirdLogAnno == null) {
                return;
            }

            ThirdLogDO thirdLogDO = thirdLogThreadLocal.get();
            thirdLogDO.setServiceName(thirdLogAnno.serviceName());
            // TODO 根据业务编码所属字段查询入参中的业务编码
            String bizCodeField = thirdLogAnno.bizCodeField();
            if (StringUtils.equalsAnyIgnoreCase(bizCodeField, "PathVariable", "UrlVariable")) {
                String params = argsArrayToString(joinPoint.getArgs());
                thirdLogDO.setBizCode(StringUtils.substring(params, 0, 50));
            } else {
                // TODO 从body中获取业务编码

            }

            // 错误信息
            if (Objects.nonNull(e)) {
                thirdLogDO.setErrMsg(e.getMessage());
            }
            // log.info("待保存日志信息：" + JSON.toJSONString(thirdLogDO));
            // 保存数据库
            thirdLogDOService.save(thirdLogDO);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        } finally {
            thirdLogThreadLocal.remove();
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private ThirdLogAnno getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        ThirdLogAnno annotation = null;
        if (method != null) {
            annotation = method.getAnnotation(ThirdLogAnno.class);
            // method上没有Log注解，则表示注解存在于类上
            if (annotation == null) {
                annotation = joinPoint.getTarget().getClass().getDeclaredAnnotation(ThirdLogAnno.class);
            }
        }
        return annotation;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if (!isFilterObject(paramsArray[i])) {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    params += jsonObj.toString() + " ";
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    public boolean isFilterObject(final Object o) {
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
}
